package se.hjartstartarregistret.m;

import javax.jdo.JDOHelper;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

public class Database {

	private static final PersistenceManagerFactory pmfInstance = JDOHelper
			.getPersistenceManagerFactory("transactions-optional");

	private static PersistenceManager openManager() {
		PersistenceManager manager = pmfInstance.getPersistenceManager();
		manager.setDetachAllOnCommit(true);
		return manager;
	}

	public static <T> T objectById(Class<T> clazz, Object id) {
		PersistenceManager manager = openManager();
		try {
			return manager.getObjectById(clazz, id);
		} catch (JDOObjectNotFoundException e) {
			return null;
		} finally {
			manager.close();
		}
	}

	public static <T> T save(T o) {
		PersistenceManager manager = openManager();
		try {
			return manager.makePersistent(o);
		} finally {
			manager.close();
		}
	}

}
